import { defineStore } from "pinia";
import {
  AddInventory, // 盘点单新增
  UpdateInventory, // 盘点单修改
  getInventoryDetail, //盘点单查询详情
  submitInventory, //盘点单提交
  getAddGoodsList, //盘点单物资列表
} from "@/utils/api/InventoryManagement/IMcheck/IMcheck";
import { dictlist } from "@/utils/api/dict/dict"; //字典列表
import { useMemberStore } from "@/stores/modules/member";
import { useToastStore } from "@/stores/modules/toast";
//新增列表头
const addListHeader = [
  "物资名称",
  "批次",
  "有效期",
  "库位",
  "库存数量",
  "实盘数量",
  "盘点差异",
  "单位",
];
export const useIMinventoryOtherStore = defineStore(
  "IMinventoryOther",
  () => {
    const memberStore = useMemberStore();
    const toastStore = useToastStore();
    const InventoryCode: any = ref(""); //盘点单号
    const addOrdetailOrEdit = ref("add"); //新增、详情、编辑
    // 新增盘点单物资表头
    const addtableHeader = addListHeader;
    // 盘点类型列表
    let TypeList: any = [];
    let inventoryTypeList: any = reactive({ TypeList });
    //获取类型列表
    const getGoodsTypeList = async () => {
      const res = await dictlist({
        DictStatus: "Normal",
        DictType: "InventoryType",
      });
      const arr = res.data.map((item: any) => {
        return {
          text: item.DictName,
          value: item.DictCode,
        };
      });
      inventoryTypeList.TypeList = arr;
    };

    /******************************盘点单***********************/
    //清空数据
    const clearData = () => {
      InventoryCode.value = "";
      addOrdetailOrEdit.value = "add";
      deleteGoodsList.delCodes = [];
      addGoodsInfoList.addGoodsList = [];
      inventoryOderDetail.inventoryDetail = {};
    };
    // 新增物资信息列表
    const addGoodsList: any = [];
    const addGoodsInfoList: any = reactive({
      addGoodsList,
      currPage: 1,
      totalPage: 0,
    });
    // 新增盘点单
    const addInventoryOrder = async (data: any) => {
      const res: any = await AddInventory({
        GodownCode: memberStore.GodownCode,
        InventoryType: data.InventoryType,
        InventoryTime: data.InventoryDate || "",
        InventoryRemarks: data.InventoryRemarks || "",
        Operator: memberStore.user_id,
      });
      InventoryCode.value = res.data.InventoryCode;
      toastStore.show = true;
      toastStore.title = "保存成功！";
      toastStore.type = "success";
      addOrdetailOrEdit.value = "edit";
      await getAddGoods({});
    };
    //编辑盘点单
    const updateInventoryOrder = async (data: any) => {
      if (isInventoryGoodsFull(addGoodsInfoList.addGoodsList)) {
        uni.showToast({
          title: "请填写完整",
          icon: "none",
          image: "",
          duration: 1500,
          mask: false,
          success: (result) => {},
        });
        return;
      }
      await UpdateInventory({
        InventoryCode: InventoryCode.value,
        GodownCode: memberStore.GodownCode,
        InventoryType: data.InventoryType,
        InventoryTime: data.InventoryDate || "",
        InventoryRemarks: data.InventoryRemarks || "",
        Operator: memberStore.user_id,
        goods: handleSubmitInventoryData(addGoodsInfoList.addGoodsList) || [], //物资列表 obj
        goodsx: deleteGoodsList.delCodes || [], //删除物资列表 codes
      });
      toastStore.show = true;
      toastStore.title = "修改成功！";
      toastStore.type = "success";
      //刷新新增物资信息列表
      await getAddGoods({ searchParam: "", pageNum: 1, pageSize: 10 });

      //清空删除物资列表
      deleteGoodsList.delCodes = [];
    };
    //提交盘点单
    const submitInventoryOrder = async (data: any) => {
      if (isInventoryGoodsFull(addGoodsInfoList.addGoodsList)) {
        toastStore.show = true;
        toastStore.title = "请填写盘点数量！";
        uni.showToast({
          title: "请填写完整",
          icon: "none",
          image: "",
          duration: 1500,
          mask: false,
          success: (result) => {},
        });
        return;
      }
      const res: any = await submitInventory({
        Operator: memberStore.user_id,
        InventoryCode: InventoryCode.value,
        GodownCode: memberStore.GodownCode,
        InventoryType: data.InventoryType,
        InventoryTime: data.InventoryDate || "",
        InventoryRemarks: data.InventoryRemarks || "",
        goods: handleSubmitInventoryData(addGoodsInfoList.addGoodsList) || [], //物资列表 obj
        goodsx: deleteGoodsList.delCodes || [], //删除物资列表 codes
      });
      console.log(res);
      if (res.code == 0) {
        toastStore.show = true;
        toastStore.title = "提交成功！";
        toastStore.type = "success";
        setTimeout(() => {
          uni.navigateBack({
            delta: 1,
          });
        }, 2000);
      }
    };
    //处理提交盘点单物资数据
    const handleSubmitInventoryData = (arr: any) => {
      let result: any = [];
      arr.forEach((obj: any) => {
        let formattedObj = {
          Uuid: obj["Uuid"] || null,
          SpecsNumber: obj["SpecsNumber"] || null,
          InventoryGoodsNumber: obj["InventoryGoodsNumber"] || null,
          Problems: obj["Problems"] || null,
          Solutions: obj["Solutions"] || null,
        };
        result.push(formattedObj);
      });
      return result;
    };
    //删除盘点单物资
    let delCodes: any = [];
    const deleteGoodsList: any = reactive({ delCodes });
    const deleteInventoryGoods = (data: any) => {
      deleteGoodsList.delCodes.push(data.Uuid);
      const index = addGoodsInfoList.addGoodsList.findIndex(
        (item: any) => item.GoodsCode == data.GoodsCode
      );
      console.log("删除物资", index, addGoodsInfoList.addGoodsList);
      addGoodsInfoList.addGoodsList.splice(index, 1);
    };
    //判断物资是否填写完整
    const isInventoryGoodsFull = (arr: any) => {
      if (arr.length == 0) {
        return false;
      }
      //判断是否有空值
      const isNull = arr.some((item: any) => {
        return (
          item.InventoryGoodsNumber == "" || item.InventoryGoodsNumber == null
        );
      });

      return isNull;
    };
    // 获取新增物资信息列表
    const getAddGoods = async (data: any) => {
      if (!InventoryCode.value) {
        toastStore.show = true;
        toastStore.title = "请先保存盘点单！";
        return;
      }
      const res: any = await getAddGoodsList({
        InventoryCode: InventoryCode.value,
        searchParam: data.searchParam || "",
        pageNum: data.pageNum || 1,
        pageSize: data.pageSize || 10,
        GodownCode: memberStore.GodownCode,
      });
      let arr: any = res.data.list;
      arr.forEach((item: any) => {
        item.isCollapse = false;
      });
      //去重
      function compareObjects(obj1: any, obj2: any) {
        // 自定义比较两个对象是否相等的逻辑
        // 返回 true 表示相等，返回 false 表示不相等
        // 这里假设对象的属性都是简单类型，没有嵌套对象
        return obj1.Uuid === obj2.Uuid;
      }

      function removeDuplicateObjects(arr: any) {
        return arr.filter((el: any, index: any, self: any) => {
          return (
            index ===
            self.findIndex((obj: any) => {
              return compareObjects(obj, el);
            })
          );
        });
      }

      if (data.searchParam) {
        addGoodsInfoList.addGoodsList = res.data.list;
      } else {
        let oldaarr = JSON.parse(JSON.stringify(addGoodsInfoList.addGoodsList));
        let newarr = [...oldaarr, ...arr];
        addGoodsInfoList.addGoodsList = removeDuplicateObjects(newarr);
      }
      addGoodsInfoList.currPage = res.data.currPage;
      addGoodsInfoList.totalPage = res.data.totalPage;
      console.log("新增物资信息列表", addGoodsInfoList.addGoodsList);
    };
    /*******************************盘点单详情************************/
    // 盘点单详情
    const inventoryOderDetail: any = reactive({});
    // 获取盘点单详情
    const getInventoryDetailData = async (data: any) => {
      const res: any = await getInventoryDetail({
        InventoryCode: data.InventoryCode,
      });
      Object.assign(inventoryOderDetail, res.data);
      console.log("盘点单详情", inventoryOderDetail);
    };
    return {
      addtableHeader,
      addGoodsInfoList,
      getAddGoods,
      InventoryCode,
      addInventoryOrder,
      addOrdetailOrEdit,
      updateInventoryOrder,
      submitInventoryOrder,
      deleteInventoryGoods,
      getInventoryDetailData,
      inventoryOderDetail,
      clearData,
      inventoryTypeList,
      getGoodsTypeList,
    };
  },
  /**********************************TODO: 持久化***********************/
  {
    // 配置持久化
    persist: {
      // 调整为兼容多端的API
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value);
        },
        getItem(key) {
          return uni.getStorageSync(key);
        },
      },
      paths: ["addtableHeader"],
    },
  }
);
